<template>
  <div class="app-container app-container-api">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="项目:">
        <el-select v-model="form.select_index" @change="select_project">
          <el-option
            v-for="(item, index) in projects"
            :key="item.project_id"
            :label="item.project_name"
            :value="index"
          >
            <span style="float: left">{{ item.project_name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.client_type }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文档名称:" style="width:480px;">
        <el-input v-model="form.doc_title" style="width:400px;" placeholder="请输入文档名称/message-type" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search_api">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="content">
      <el-tree
        ref="tree"
        class="left"
        :data="tree_data"
        :props="defaultProps"
        :filter-node-method="filterNode"
        default-expand-all
        :highlight-current="true"
        node-key="doc_id"
        @node-click="tree_click"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span class="btn">
            <i title="新增分类" style="color:#67C23A;font-size: 20px" class="el-icon-folder-add" @click.stop="add_classify(data)" />
            <i v-show="!data.children" title="新增文档" style 折叠树点击新增文档="color:#67C23A;font-size: 20px" class="el-icon-edit-outline" @click.stop="add_api(data)" />
            <i v-show="!data.children" title="删除分类" style="color: #F56C6C;font-size: 20px" class="el-icon-delete" @click.stop="delete_api(data)" />
          </span>
        </span>
      </el-tree>
      <div class="right">
        <template v-if="show_detail">
          <el-page-header title="返回列表" :content="levels.map((i)=>{return i.doc_title}).join('/')" @back="show_detail = false" />
          <api-view :doc-id="doc_id" :space-id="spaceid" :project-id="project_id" :client-type="client_type" :levels="levels" @edit-success="edit_success" @edit-cancel="show_detail = false" />
        </template>
        <template v-else>
          <el-table :key="select_row.doc_id" :loading="table_loading" :data="tableData">
            <el-table-column prop="doc_title" label="文档标题">
              <template slot-scope="scope">
                <el-link v-if="scope.row.has_unsolved" type="danger" @click.stop="find_one(scope.row)">
                  <span v-for="i in scope.row.levels" :key="i.doc_id">{{ i.doc_title }} / </span>
                  <span>{{ scope.row.doc_title }}</span>
                </el-link>
                <el-link v-else-if="scope.row.has_unconfirmed" type="primary" @click.stop="find_one(scope.row)">
                  <span v-for="i in scope.row.levels" :key="i.doc_id">{{ i.doc_title }} / </span>
                  <span>{{ scope.row.doc_title }}</span>
                </el-link>
                <el-link v-else @click.stop="find_one(scope.row)">
                  <span v-for="i in scope.row.levels" :key="i.doc_id">{{ i.doc_title }} / </span>
                  <span>{{ scope.row.doc_title }}</span>
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="editer" label="编辑者" width="160" />
            <el-table-column prop="edit_time_display" label="更新时间" width="200" />
            <el-table-column label="操作" width="160">
              <template slot-scope="scope">
                <i v-if="scope.row.owner" class="el-icon-delete cp owner" @click="delete_doc(scope.row)" />
                <i v-else-if="scope.row.partner" class="el-icon-message-solid cp lineheight" />
                <i v-else title="关注" class="el-icon-message-solid cp" @click="attention(scope)" />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>
    <api-add
      ref="api-add"
      :display="dialog_show"
      :form="form"
      @dialog-sure="dialog_sure"
      @dialog-close="dialog_show = false"
    />
    <select-type ref="select-type" :display="select_type_display" @dialog-sure="select_dialog_sure" @dialog-close="select_type_display = false" />
  </div>
</template>

<script>
import apiAdd from './components/api-add'
import selectType from './components/select-type'
import apiView from './components/api-view'
import { project_list, find_list, find_search, del, find_classify, get_tables, attention as to_attention } from './api'
import tree from '@/utils/tree-data'
import get_parents from '@/utils/get-parents'
import { set, get } from '@/utils/storage'

export default {
  components: {
    apiAdd,
    selectType,
    apiView
  },
  data() {
    return {
      doc_id: '',
      project_id: '',
      spaceid: '',
      client_type: '',
      levels: [],
      show_detail: false,
      table_loading: false,
      dialog_show: false,
      select_type_display: false,
      form: {
        doc_title: '',
        select_index: 0
      },
      tree_data: [],
      defaultProps: {
        children: 'children',
        label: 'doc_title'
      },
      tableData: [],
      select_row: {},
      classifys: [],
      projects: [],
      value: '龙须面'
    }
  },
  mounted() {
    this.render_select()
  },
  methods: {
    async render_select() {
      this.projects = await project_list()
      const index = this.$route.query ? this.projects.findIndex((i) => {
        return i.project_id === this.$route.query.project_id && i.client_type === this.$route.query.type
      }) : 0
      this.form.select_index = index === -1 ? 0 : index
      this.project_id = this.projects[this.form.select_index].project_id
      this.spaceid = this.projects[this.form.select_index].spaceid
      this.client_type = this.projects[this.form.select_index].client_type
      this.login()
      this.render_list()
      this.render_tree()
    },
    login() {
      get_tables(this.project_id).then((res) => {
        set(this.project_id, JSON.stringify(res.tables))
        set('sessionid', res.sessionid)
      })
    },
    render_list() {
      const user_code = get('user_code')
      // const role = get('role')
      this.select_row = {}
      this.table_loading = true
      find_list(this.spaceid, this.client_type).then(data => {
        this.table_loading = false
        this.tableData = data.map((item) => {
          return {
            ...item,
            owner: item.creater === user_code,
            partner: item.partners ? item.partners.indexOf(user_code) !== -1 : false
          }
        })
      })
    },
    render_tree() {
      find_classify(this.spaceid, this.client_type).then(data => {
        this.classifys = data
        this.tree_data = tree(data, 'doc_parent_id', 'doc_id')
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 根据文档名称 条件查询
    search_api() {
      this.select_row = {}
      this.form.select_index
      find_search('', this.form.doc_title, this.spaceid, this.client_type).then(data => {
        this.tableData = data
      })
      this.render_tree()
    },
    // 新增分类
    // 新增同级或子级 'brothers' 'son'
    add_classify(data) {
      this.select_type_display = true
      this.$refs['select-type'].show(data)
    },
    // 折叠树点击新增文档
    add_api(data) {
      // this.dialog_show = true
      // this.$refs['api-add'].show('add', data.doc_id, data.doc_parent_id)
      const res = get_parents(data.doc_parent_id, this.classifys, 'doc_parent_id', 'doc_id')
      res.push(data)
      this.doc_id = ''
      this.levels = res
      this.show_detail = true
    },
    dialog_sure() {
      this.render_list()
    },
    delete_api(data) {
      this.$confirm('确定删除分类吗', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((ret) => {
        // 用户确认
        del(data.doc_id).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.render_tree()
          if (this.select_row && this.select_row.doc_id === data.doc_id) {
            this.select_row = {}
            this.render_list()
          }
          return
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 查询单条服务数据
    find_one({ doc_id, levels }) {
      this.doc_id = doc_id
      this.levels = levels
      this.show_detail = true
    },
    // 修改文档 update
    update(type, data) {
      this.$refs['api-add'].show(type, data.doc_id, data.doc_parent_id)
      this.dialog_show = true
    },
    // 折叠树点击
    tree_click(row) {
      this.select_row = row
      this.table_loading = true
      if (!row.children) {
        this.show_detail = false
        find_search(row.doc_id, '', this.$route.query.spaceid, this.$route.query.type).then(data => {
          this.table_loading = false
          this.tableData = data
        })
      }
    },
    // 选中左侧树
    select_tree(row) {
      this.$refs.tree.setCurrentKey(row.doc_id)
      this.tree_click(row)
    },
    select_dialog_sure() {
      this.select_type_display = false
      this.render_tree()
    },
    async attention(scope) {
      this.tableData[scope.$index].partner = true
      const user = get('user_code')
      await to_attention(scope.row.doc_id, user)
      this.$message({
        message: '关注服务成功',
        type: 'success',
        duration: 2 * 1000
      })
      return
    },
    delete_doc(row) {
      this.$confirm('确定删除文档吗', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((ret) => {
        // 用户确认
        del(row.doc_id, 'doc').then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.render_list()
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 修改成功
    edit_success() {
      this.show_detail = false
      this.render_list()
    },
    select_project(index) {
      this.project_id = this.projects[index].project_id
      this.spaceid = this.projects[index].spaceid
      this.client_type = this.projects[index].client_type
    }
  }
}
</script>

<style lang='scss'>
.app-container-api {
  .cell {
    font-size: 15px;
    span {
      font-size: 15px;
    }
  }
  .cp {
    cursor: pointer;
    font-size: 15px;
  }
  .owner {
    color: #F56C6C;
  }
  .lineheight {
    color: #E6A23C;
  }
  .el-icon-s-opportunity {
    &:hover {
      color: #E6A23C;
    }
  }
  .content {
    display: flex;
    .left {
      display: inline-block;
      width: 400px;
      border-right: 1px solid #eee;
      padding-right: 20px;
      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
        padding-right: 8px;
      }
    }
    .right {
      display: inline-block;
      width: calc(100% - 450px);
      padding-left: 20px;
    }
  }
}
</style>
